package org.looop.studio.bean.scope.extension;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.looop.studio.bean.domain.BeanDefinition;
import org.looop.studio.bean.factory.BeanFactory;
import org.looop.studio.bean.scope.BeanScope;

public class ThreadLocalScope implements BeanScope {
	private ThreadLocal<Map<String, Object>> threadLocalBeanPool = new ThreadLocal<Map<String, Object>>(){
		protected java.util.Map<String,Object> initialValue() {
			return new HashMap<String, Object>();
		};
	};
	
	@Override
	public Object getBean(BeanFactory factory, BeanDefinition beanDefinition)
			throws InstantiationException, IllegalAccessException,
			ClassNotFoundException, IllegalArgumentException,
			SecurityException, InvocationTargetException, NoSuchMethodException {
		String id = beanDefinition.getId();
		Map<String, Object> beanPool = threadLocalBeanPool.get();
		if (beanPool.get(id) == null) {
			Object bean = factory.createBean(beanDefinition);
			beanPool.put(id, bean);
			return bean;
		} else {
			return beanPool.get(id);
		}
	}

}
